<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import = "com.google.appengine.api.users.UserService" %>
<%@ page import = "com.google.appengine.api.users.User" %>
<%@ page import = "imoney.server.util.CookieBuilderServer" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.util.ArrayList" %>
<%@ page import = "imoney.shared.model.Person" %>
<%@ page import = "com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import = "imoney.shared.Statics" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Logout and Redirection to Application's home</title>
</head>
<body>
	<%
		UserService userService = UserServiceFactory.getUserService();
		
		// searching for the cookie of the registered user, in order to remove the Person from the list and delete the cookie
		for(Cookie cook : request.getCookies()) {
		
			if(cook.getName().equals(Statics.Cookie_INDEX_OF_PERSON)) {
		
		// take care of the list
		int position = CookieBuilderServer.readPosition(cook);
		String googleID = CookieBuilderServer.readUserId(cook);
		@SuppressWarnings("unchecked")
		ArrayList<Person> personList = (ArrayList<Person>) application.getAttribute(Statics.Context_LIST_PERSONS);
		if (position < personList.size() && personList.get(position)!=null
				&& personList.get(position).getUserID().equals(googleID)) {
			personList.set(position, null); // the position musn't be deleted, because if it is, all the indexes superior to this one
											// will have a -1 offset, and will no longer be corresponding to cookies stored client side.
		}
		
		// delete the cookie on the client side
		cook.setMaxAge(0);
		cook.setPath("/");
		response.addCookie(cook);
		
		break;
			}
		}
		
		String logoutUrl = userService.createLogoutURL(Statics.LOGGIN_URL); // redirecting to userServlet
		response.setHeader("cache-control", "no-cache");
		response.sendRedirect(logoutUrl);
	%>
</body>
</html>